<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="shouquan">授权</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button icon="el-icon-refresh" size="mini" @click="tongbu">同步商品</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleJiankong"
        >开始监控</el-button>
      </el-col>
      <div v-show="show">
        <el-col :span="10" :offset="6">
          <div>
            <el-progress :percentage="percentage" color="#13ce66" :stroke-width="18" text-inside />
          </div>
        </el-col>
        <el-col :span="3">
          <div style="text-align: right;">
            已{{action}}商品数 : {{count}} / {{totalCount}}
          </div>
        </el-col>
      </div>
    </el-row>
    <el-table border v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column show-overflow-tooltip label="商品编码" align="center" prop="goodsId" width="120"/>
      <el-table-column show-overflow-tooltip label="商品外部编码" align="center" prop="outerGoodsId" width="180"/>
      <el-table-column show-overflow-tooltip label="商品名称" align="center" prop="goodsName"/>
      <el-table-column label="是否多SKU" align="center" prop="isMoreSku" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.isMoreSku == 0">否</span>
          <span v-if="scope.row.isMoreSku == 1">是</span>
        </template>
      </el-table-column>
      <el-table-column label="商品缩略图" align="center" prop="thumbUrl" width="100">
        <template slot-scope="scope">
          <ImagePreview
            :width=50 :height=50
            :src="scope.row.thumbUrl"
            :preview-src-list="[scope.row.thumbUrl]"/>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip label="下架原因" align="center" prop="reason"/>
    </el-table>

<!--    <pagination-->
<!--      v-show="total>0"-->
<!--      :total="total"-->
<!--      :page.sync="queryParams.pageNum"-->
<!--      :limit.sync="queryParams.pageSize"-->
<!--      @pagination="getList"-->
<!--    />-->
  </div>
</template>

<script>
import { pddGoodsList } from "@/api/system/pddGoods";
import {pddSyncPddData,jiankongPddData} from "@/api/system/pdd";
export default {
  name: "Jiankong",
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 拼多多商品列表格数据
      goodsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsId: null,
        goodsName: null,
        goodsQuantity: null,
        goodsReserveQuantity: null,
        imageUrl: null,
        isMoreSku: null,
        isOnsale: null,
        thumbUrl: null,
        createdAt: null,
        ownerId: null,
        ownerName: null,
        userId: null
      },
      mallId : null,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        goodsId: [
          { required: true, message: "商品编码不能为空", trigger: "blur" }
        ],
      },
      //进度条百分比
      percentage : 0,
      //总数
      totalCount : 0,
      //已操作数
      count : 0,
      //操作名成
      action: "同步",
      //是否显示信息
      show: false
    };
  },
  created() {
    const mallId = this.$route.params && this.$route.params.mallId;
    this.mallId = mallId;
    this.queryParams.ownerId = mallId;
    this.initSocket();
    // this.getList();
  },
  methods: {
    /** 查询拼多多商品列列表 */
    getList() {
      this.loading = true;
      this.queryParams.ownerId = this.mallId;
      pddGoodsList(this.queryParams).then(response => {
        this.goodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        goodsId: null,
        goodsName: null,
        goodsQuantity: null,
        goodsReserveQuantity: null,
        imageUrl: null,
        isMoreSku: null,
        isOnsale: null,
        thumbUrl: null,
        createTime: null,
        ownerId: null,
        ownerName: null,
        userId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加拼多多商品列";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getGoods(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改拼多多商品列";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateGoods(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGoods(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除拼多多商品列编号为"' + ids + '"的数据项？').then(function() {
        return delGoods(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/goods/export', {
        ...this.queryParams
      }, `goods_${new Date().getTime()}.xlsx`)
    },
    shouquan(){
      const url = "http://27.128.175.119/prod-api/pdd/pddCallback";
      const encodedUrl = encodeURIComponent(url);
      window.location.href = "https://fuwu.pinduoduo.com/service-market/auth?response_type=code&client_id=2ba77f6df16945b6860b9fbb3b9cf8ad&redirect_uri="+encodedUrl+"&state=1";
    },
    tongbu(){
      this.action = "同步"
      this.show = true;
      pddSyncPddData(this.mallId).then(response => {

      });
    },
    handleJiankong(){
      this.action = "监控"
      this.show = true;
      jiankongPddData(this.queryParams).then(response => {

      });
    },

    initSocket(){
      var _this = this;
      this.socket = new WebSocket(`ws://localhost:8080/ws/${this.$store.getters.userId}`); // 将用户ID动态拼接到WebSocket地址中

      // 监听 WebSocket 连接打开事件
      this.socket.onopen = function(event) {
        console.log("WebSocket 连接已打开");
        // 每隔一定时间发送心跳包
        setInterval(() => {
          _this.sendHeartbeat();
        }, 10000); // 例如，每隔 30 秒发送一次心跳包
      };

      this.socket.onmessage = (event) => {
        // 处理收到的消息
        var jsonObject = JSON.parse(event.data);
        if(jsonObject.action == "total") {
          this.totalCount = jsonObject.total;
        }
        if(jsonObject.action == "tongbu") {
          this.count = jsonObject.count;
          this.percentage = Math.round(this.count / this.totalCount * 100);
        }
        if(jsonObject.action == "list") {
          this.goodsList.push(jsonObject.data);
          this.count = jsonObject.count;
          this.percentage = Math.round(this.count / this.totalCount * 100);
        }
      };

      this.socket.onclose = () => {
        console.log('WebSocket closed');
        // 连接关闭后的处理
        console.log("WebSocket 连接已关闭");
        // 在连接关闭时执行断线重连的逻辑
        // 例如，延迟一段时间后重新创建 WebSocket 连接
        setTimeout(function() {
          _this.initSocket(); // 重新创建 WebSocket 连接
        }, 3000); // 例如，延迟 3 秒后重新连接
      };

      this.socket.onerror = (error) => {
        console.error('WebSocket error:', error);
        // 错误处理
      };
    },
    sendHeartbeat() {
      if (this.socket.readyState === WebSocket.OPEN) {
        // 如果 WebSocket 连接处于打开状态，则发送心跳包
        this.socket.send(JSON.stringify({heartbeat:"1"}));
      }
    },




  }
};
</script>
<style>

.item .el-form-item__label{
  margin-left: 14px;
}

</style>
